/**
 * 易驰护运 - DeleteCar
 * http://menger.me
 * 订单详情更换车辆
 * @桓桓
 */

'use strict';

import React from 'react'
import {ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View} from 'react-native'
import {ListHeaderLoading,} from '../../components'
import {inject, observer} from 'mobx-react'

@inject('loginStore')
@observer
export default class DeleteCar extends React.Component {
    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            loading: false,
            isRefreshing: false,
            order_vehicle_list: [],
            order_vehicle: [],
            shipper_remarks: '',
        }
    }

    componentDidMount() {
        this.requestData();
    }

    _onRefresh = async () => {
        this.setState({isRefreshing: true});
        this.requestData();
        setTimeout(() => this.setState({isRefreshing: false}), 500);
    };
    
    requestData = async() => {
        let {item} = this.params;
        let url = ServicesApi.ORDER_CANCEL_VEHICLE_LIST;
        let data = {
            order_id: item.id,
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                order_vehicle_list: result.data.dataList, 
                loading: false,
            });
        }
    }

    // 选中或取消选中车辆
    changeLeisure = (key) => {
        let {order_vehicle} = this.state;
        let arr = order_vehicle.slice()
        if (order_vehicle.includes(key)) {
            arr.splice(order_vehicle.indexOf(key), 1)
        } else {
            arr.push(key)
        }
        console.log('arr------------->', arr)
        this.setState({
            order_vehicle: arr
        })
    }

    onSubmit = async () => {
        let {item, onRefresh} = this.params;
        let {shipper_remarks, order_vehicle} = this.state;
        let carArray = [];
        order_vehicle.forEach(element => {
            carArray.push(element.id)
        });
        if (shipper_remarks === '') {
            ToastManager.message('请填写取消原因');
            return
        }
        let cancel_vehicle_id = carArray.join(',')
        if (cancel_vehicle_id === '') {
            ToastManager.message('请选择选择被取消的车辆');
            return
        }
        let url = ServicesApi.ORDER_CANCEL_VEHICLE_APPLY;
        let data = {
            order_id: item.id,
            cancel_reasons: shipper_remarks,
            cancel_vehicle_id: cancel_vehicle_id,
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.message(result.msg);
            setTimeout(() => {
                onRefresh && onRefresh()
                RouterHelper.goBack()
            }, 1000);
        } else {
            ToastManager.message(result.msg);
        }
    }

    oldCarList = (data) => {
        let {order_vehicle} = this.state;
        if (data.length == 0) {
            return <Text style={styles.doNotHaveCar} numberOfLines={1}>暂无符合要求车辆</Text>
        }
        let contain = data.map((item, index) => {
            return (
                <TouchableOpacity
                    key={index}
                    style={[styles.carCard, order_vehicle.includes(item) && {backgroundColor: '#CAF2F7'}]}
                    onPress={() => this.changeLeisure(item)}
                >
                    <View style={styles.carCardHeader}>
                        <View style={styles.carCardHeaderBall}/>
                        <Text style={styles.carCardHeaderText}>{item.status_text}</Text>
                    </View>
                    <View style={styles.carCardLine}>
                        <Text style={styles.carCardLineText}>车牌号：{item.vehicle_number}</Text>
                        <Text style={styles.carCardLineText}>司机姓名：{item.driver_name}</Text>
                    </View>
                    <View style={styles.carCardLine}>
                        <Text style={styles.carCardLineText}>车辆类型：{item.vehicle_type_text}</Text>
                        <Text style={styles.carCardLineText}>车辆载重：{item.vehicle_weight}吨</Text>
                    </View>
                    {
                        item.id == order_vehicle &&
                        <ImageView
                            resizeMode={'contain'}
                            style={styles.carCardImg}
                            source={Images.icon_choice_car}
                        />
                    }
                </TouchableOpacity>
            )
        })
        return contain
    }
    
    render() {
        let {loading, shipper_remarks, order_vehicle_list} = this.state;
        return (
            <PageContainer 
                loading={loading}
                style={styles.container}
                fitIPhoneX={true} 
                fitNotchedScreen={Predefine.isNotchedScreen}
            >
                <NavigationBar title={'取消车辆'} style={styles.navigationBar}/>
                <View style={styles.headerPadding}/>
                <ScrollView
                    style={styles.content}
                    refreshControl={<ListHeaderLoading onRefresh={this._onRefresh} refreshing={this.state.isRefreshing}/>}
                >
                    <View style={styles.card}>
                        <View style={styles.cardHeader}>
                            <View style={styles.cardHeaderBall}><View style={styles.cardHeaderBallCenter}/></View>
                            <Text style={styles.cardHeaderText} numberOfLines={1}>取消原因</Text>
                        </View>
                        <TextInput
                            multiline={true}
                            textAlignVertical={'top'}
                            style={styles.textArea}
                            placeholderTextColor={'#999'}
                            defaultValue={shipper_remarks}
                            placeholder={'请输入您的备注信息...'}
                            onChangeText={(text) => this.setState({shipper_remarks: text})}
                        />
                    </View>
                    <View style={styles.card}>
                        <View style={styles.cardHeader}>
                            <View style={styles.cardHeaderBall}><View style={styles.cardHeaderBallCenter}/></View>
                            <Text style={styles.cardHeaderText} numberOfLines={1}>选择需要取消的的车辆</Text>
                        </View>
                        {this.oldCarList(order_vehicle_list)}
                    </View>
                </ScrollView>
                <View style={styles.bottomBtn}>
                    <Button
                        style={styles.btn}
                        title={'提交取消车辆审核'}
                        titleStyle={styles.btnTitle}
                        resizeMode={'cover'}
                        backgroundImage={Images.img_btn_bg1}
                        onPress={() => this.onSubmit()}
                    />
                </View>
            </PageContainer>
        );
    }
}

const DominantColor = '#00BFCC';
const contentWidth = Predefine.screenWidth - 20;
const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    navigationBar: {
        zIndex: 10,
        position: 'absolute',
    },
    headerPadding: {
        height: NAV_BAR_HEIGHT,
    },

    card: {
        marginBottom: 10,
        backgroundColor: '#fff',
        paddingHorizontal: 15,
    },
    cardHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 40,
    },
    cardHeaderBall: {
        width: 12,
        height: 12,
        borderRadius: 6,
        backgroundColor: DominantColor,
        marginRight: 6,
        alignItems: 'center',
        justifyContent: 'center',
    },
    cardHeaderBallCenter: {
        height: 6,
        width: 6,
        borderRadius: 3,
        backgroundColor: '#fff',
    },
    cardHeaderText: {
        color: '#333',
        fontSize: 13,
        fontWeight: 'bold',
    },
    textArea: {
        borderWidth: 1,
        borderColor: '#e1e1e1',
        borderRadius: 5,
        marginBottom: 15,
        fontSize: 14,
        padding: 10,
        height: 80,
    },

    doNotHaveCar: {
        paddingBottom: 10,
        fontSize: 14,
        color: '#666',
    },
    carCard: {
        borderWidth: Predefine.minPixel,
        borderColor: '#e1e1e1',
        borderRadius: 5,
        marginBottom: 10,
        paddingHorizontal: 10,
        paddingVertical: 5,
    },
    carCardHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 25,
    },
    carCardHeaderBall: {
        width: 10,
        height: 10,
        borderRadius: 5,
        marginRight: 6,
        backgroundColor: DominantColor,
    },
    carCardHeaderText: {
        color: DominantColor,
        fontSize: 12,
    },
    carCardLine: {
        height: 25,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    carCardLineText: {
        flex: 1,
        fontSize: 12,
        color: '#333',
    },
    carCardImg: {
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: 28,
        height: 30,
    },
    
    bottomBtn: {
        paddingHorizontal: 15,
        paddingVertical: 10,
        backgroundColor: '#fff',
    },
    btn: {
        backgroundColor: DominantColor,
    },
});